/*
 * @Author       : wfl
 * @LastEditors  : wfl
 * @description  :
 * @updateInfo   :
 * @Date         : 2023-07-26 10:48:01
 * @LastEditTime : 2023-07-27 11:48:27
 */
// updateOnPackageUpdate.js
import axios from 'axios'
import pkg from '../../../package.json'

async function getLatestVersion(packageName: string) {
  try {
    const response = await axios.get(`https://registry.npmjs.org/${packageName}/latest`)
    return response.data.version
  }
  catch (error) {
    console.error(`Error fetching latest version for package "${packageName}":`, error)
    return null
  }
}

export default function updateOnPackageUpdate(packageName: string) {
  let latestVersion: any = null

  return {
    name: 'update-on-package-update',
    async handleHotUpdate({ file, server }: any) {
      if (file.endsWith('package.json')) {
        try {
          const packageJson = pkg
          const currentVersion = packageJson.dependencies[packageName as keyof typeof packageJson.dependencies]

          if (!latestVersion)
            latestVersion = await getLatestVersion(packageName)

          if (currentVersion !== latestVersion) {
            console.info(`Package "${packageName}" has been updated to version ${latestVersion}. Running package manager...`)
            await server.execute('npm install')
            console.info('Package install complete.')
            latestVersion = currentVersion
          }
          else {
            console.info(`Package "${packageName}" is up to date.`)
          }
        }
        catch (error) {
          console.error('Error updating packages:', error)
        }
      }
    }
  }
}
